import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import '../../../style/widget_style.dart';
import '../../../widgets/AppHeader.dart';
import '../../../widgets/CommonWidgets.dart';
import '../controllers/photo_translate_controller.dart';
import 'package:camerawesome/camerawesome_plugin.dart';
import '../views/result.dart';
import 'ScanLineMovingBar.dart';
import 'capture_button.dart';

class PhotoTranslateView extends GetView<PhotoTranslateController> {
  const PhotoTranslateView({super.key});

  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Obx(
              () => Column(
            children: [
              Container(
                height: 160.0,
                child: Stack(
                  children: [
                    Container(
                      // child: AvatarScreen()
                      child: SvgPicture.asset(
                        "assets/images/header_part_bg.svg",
                        width: Get.width,
                      ),
                    ),
                    AppHeader.obtainHeaderWithoutRightPartCal('拍照翻译',
                        controller.clearAll
                    ),
                    Positioned(
                      top: 90.0,
                      left: 15.w,
                      right: 15.w,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: InkWell(
                              onTap: () {
                                if(controller.pageState.value == 'loading'){
                                  return;
                                }
                                controller.chooseFromLanguages();
                              },
                              child: Container(
                                width: 128.w,
                                height: 48.h,
                                padding: EdgeInsets.all(8.w),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  boxShadow: [
                                    CommonWidgets.getBoxShadow()
                                  ],
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(
                                    8,
                                  ), // Optional: add border radius
                                ),
                                child: Text(
                                  '${controller.fromLanFlagDisplay.value}',
                                  style: AppStyleThemeData.normal_bold,
                                  maxLines: 1,// 最多显示2行
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ),
                          ),
                          InkWell(
                            onTap: (){
                              if(controller.pageState.value == 'loading'){
                                return;
                              }
                              controller.switchLang();
                            },
                            child: Container(
                                padding: EdgeInsets.all(14.w),
                                height: 48.h,
                                width: 65.w,
                                margin: EdgeInsets.fromLTRB(16, 0, 16, 0),
                                decoration: BoxDecoration(
                                  boxShadow: [
                                    CommonWidgets.getBoxShadow(),
                                  ],
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(
                                    8,
                                  ), // Optional: add border radius
                                ),
                                child: Image.asset('assets/images/icon_index_lang_exchange.png')
                            ),
                          ),

                          Expanded(
                            child: InkWell(
                              onTap: () {
                                if(controller.pageState.value == 'loading'){
                                  return;
                                }
                                controller.chooseToLanguages();
                              },
                              child: Container(
                                padding: EdgeInsets.only(left: 10.w),
                                width: 126.w,
                                height: 48.h,
                                decoration: BoxDecoration(
                                  boxShadow: [
                                    CommonWidgets.getBoxShadow(),
                                  ],
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(
                                    8,
                                  ), // Optional: add border radius
                                ),

                                child:Center(
                                  child: Text(
                                    '${controller.toLanFlagDisplay.value.trim()}',
                                    style: AppStyleThemeData.normal_bold,
                                    maxLines: 1, // 最多显示2行
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),

                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Visibility(
                visible: (controller.pageState.value == 'pickFromCamera'),
                child: Expanded(
                  child:
                      Stack(children: [
                        CameraAwesomeBuilder.awesome(
                          theme: AwesomeTheme(
                              bottomActionsBackgroundColor:Color(0xFF666666),
                              buttonTheme: AwesomeButtonTheme(backgroundColor: Colors.black.withValues(alpha: 0.5),
                                  iconSize: 16,padding: const EdgeInsets.all(8))

                          ),
                          // refrence:https://docs.page/Apparence-io/camera_awesome/getting_started/awesome-ui
                          saveConfig: SaveConfig.photoAndVideo(
                            initialCaptureMode: CaptureMode.photo,
                            photoPathBuilder: (sensors) async {
                              final Directory extDir = await getTemporaryDirectory();
                              print('checkextDir ${extDir}');
                              final photoDir = await Directory(
                                '${extDir.path}/photoTranslateDir',
                              ).create(recursive: true);
                              print('checkphotoDir ${photoDir}');
                              if (sensors.length == 1) {
                                final String filePath =
                                    '${photoDir.path}/${DateTime.now().millisecondsSinceEpoch}.jpg';
                                return SingleCaptureRequest(filePath, sensors.first);
                              }
                              // Separate pictures taken with front and back camera
                              return MultipleCaptureRequest({
                                for (final sensor in sensors)
                                  sensor:
                                  '${photoDir.path}/${sensor.position == SensorPosition.front ? 'front_' : "back_"}${DateTime.now().millisecondsSinceEpoch}.jpg',
                              });
                            },
                          ),
                          sensorConfig: SensorConfig.single(
                            flashMode: FlashMode.none,
                          ),
                          onMediaCaptureEvent: (event) {
                            switch ((event.status, event.isPicture, event.isVideo)) {
                              case (MediaCaptureStatus.capturing, true, false):
                                debugPrint('Capturing picture...');
                              case (MediaCaptureStatus.success, true, false):
                                event.captureRequest.when(
                                  single: (single) {
                                    print('sing ${single}');
                                    debugPrint('Picture saved: ${single.file?.path}');
                                    controller.sendImage(
                                      single.file?.path,
                                      MediaQuery.of(context).size.width,
                                      context,
                                    );
                                  },
                                  multiple: (multiple) {
                                    multiple.fileBySensor.forEach((key, value) {
                                      debugPrint(
                                        'multiple image taken: $key ${value?.path}',
                                      );
                                    });
                                  },
                                );
                              case (MediaCaptureStatus.failure, true, false):
                                debugPrint(
                                  'Failed to capture picture: ${event.exception}',
                                );
                              case (MediaCaptureStatus.capturing, false, true):
                                debugPrint('Capturing video...');
                              case (MediaCaptureStatus.success, false, true):
                                event.captureRequest.when(
                                  single: (single) {
                                    debugPrint('Video saved: ${single.file?.path}');
                                  },
                                  multiple: (multiple) {
                                    multiple.fileBySensor.forEach((key, value) {
                                      debugPrint(
                                        'multiple video taken: $key ${value?.path}',
                                      );
                                    });
                                  },
                                );
                              case (MediaCaptureStatus.failure, false, true):
                                debugPrint(
                                  'Failed to capture video: ${event.exception}',
                                );
                              default:
                                debugPrint('Unknown event: $event');
                            }
                          },
                          topActionsBuilder:
                              (state) => AwesomeTopActions(
                            padding: const EdgeInsets.all(0),
                            state: state,
                            children: [],
                          ),
                          // Show some Text with same background as the bottom part
                          middleContentBuilder: (state) {
                            return Column(
                              children: [
                                // const Spacer(),
                                // Use a Builder to get a BuildContext below AwesomeThemeProvider widget
                                Builder(
                                  builder: (context) {
                                    return Container(
                                      // Retrieve your AwesomeTheme's background color
                                      color:
                                      AwesomeThemeProvider.of(
                                        context,
                                      ).theme.bottomActionsBackgroundColor,
                                      child: const Align(
                                        alignment: Alignment.bottomCenter,
                                      ),
                                    );
                                  },
                                ),
                              ],
                            );
                          },
                          // Show Flash button on the left and Camera switch button on the right
                          bottomActionsBuilder:
                              (state) =>Container(
                              height: 80,
                              child:AwesomeBottomActions(
                                  state: state,
                                  left: InkWell(
                                    onTap: () {
                                      controller.uploadLocalImage(
                                        MediaQuery.of(context).size.width,
                                        context
                                      );
                                    },
                                    child: Container(
                                      width:32,
                                      height:32,
                                      decoration: BoxDecoration(
                                        color: Colors.black.withValues(alpha: 0.5),
                                        borderRadius: BorderRadius.circular(16),
                                      ),
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          SvgPicture.asset(
                                            'assets/images/icon_photo_bottom_left.svg',
                                            width: 16,
                                            height: 16,
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),

                                  right: AwesomeFlashButton(
                                    state: state,
                                    onFlashTap: (sensorConfig, flashMode) {
                                      print('flashMode ${flashMode}');
                                      final newFlashMode =
                                      flashMode == FlashMode.none
                                          ? FlashMode.always
                                          : FlashMode.none;
                                      sensorConfig.setFlashMode(newFlashMode);
                                    },
                                  ),
                                  captureButton:
                                  MyCaptureButton(state: state,pageState: controller.pageState.value
                                  )
                              )),


                        ),

                      ],)

                ),

              ),

              if(controller.pageState.value == 'loading')Expanded(
                  child:Stack(children: [
                    Image.file(File(controller.picPath.value)),
                    ScanLineMovingBar(
                      width: MediaQuery.of(context).size.width,
                      height: controller.picHight.value,
                      lineColor: Colors.redAccent,
                      lineHeight: 2,
                      animDuration: Duration(seconds: 2),
                    )
                  ],)
              ),
              if(controller.pageState.value == 'result')Expanded(
                child: BlurImage(
                  path: controller.picPath.value,
                  result: controller.picResult,
                  screenWidth: MediaQuery.of(context).size.width,
                  currentSrc: controller.currentSrc.value,
                  currentTgt: controller.currentTgt.value,
                  srcLang: controller.fromLanFlagDisplay.value,
                  tgtLang: controller.toLanFlagDisplay.value,
                  translateVoice: controller.translateVoice,
                  changePageState:controller.changePageState,
                  addPhoto:controller.addPhoto,
                  clickDelete:controller.clickDelete,
                  galleryData:controller.galleryData.value,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
